package com.jysz.certificate.service.system;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.cm.CertificationCoreDao;
import com.jysz.certificate.persistence.dao.cs.tn.TheNetworkDao;
import com.jysz.certificate.persistence.dao.system.ShopDao;
import com.jysz.certificate.persistence.dao.system.TreatyDao;
import com.jysz.certificate.persistence.enums.CertificationType;
import com.jysz.certificate.persistence.enums.CopyOfCertificationImporting;
import com.jysz.certificate.persistence.enums.PostType;
import com.jysz.certificate.persistence.model.cm.Certification;
import com.jysz.certificate.persistence.model.system.Brand;
import com.jysz.certificate.persistence.model.system.Organization;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.persistence.model.system.Treaty;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.cm.CertificateService;
import com.jysz.certificate.service.cm.CertificationService;
import com.jysz.certificate.utils.DateUtil;
import com.jysz.webcore.ssh.orm.hibernate.support.Page;
import com.jysz.webcore.ssh.service.EntityService;
import com.jysz.webcore.utils.ReflectionUtils;


@Service
public class ShopService  extends EntityService<Shop, Long, ShopDao>{
	
	@Resource
	private ShopDao shopDao;
	@Resource
	private UserService us;
	@Resource
	private CertificationCoreDao certificationDao;
	@Resource
	private TreatyDao treatyDao;
	@Resource
	private TheNetworkDao theNetworkDao;
	@Resource
	private CertificateService certificateService;
	@Resource
	private OrganizationService organizationService;
	@Resource
	private CertificationService certificationService;
	
	
	public List<Shop> getAllShop(){
		return this.findAll();
	}
	
	
	public boolean updateShopByOrg(Long shopId){
		if(certificationDao.findCertificationByShop(shopId)){
			Criteria criteria = shopDao.createCriteria();
			criteria.add(Restrictions.eq("id", shopId));
			Shop shop = (Shop) criteria.uniqueResult();
			shop.setArea(null);
			shopDao.save(shop);
			return true;
		}
		return false;
	}
	
	
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map> findStoreCount(Shop shop,Brand brand, Long financialId, Long userId) {
		
		Criteria criteria = certificationDao.createCriteria();
		
		criteria.setProjection(Projections.projectionList().add(Projections.alias(Projections.groupProperty(Certification.SHOP),"shop")).add(Projections.alias(Projections.rowCount(), "cfCount")));
		
		criteria.add(Restrictions.eq("state",  CertificationType.INSTOCK));
//		criteria.add(Restrictions.sqlRestriction("count(*) > 0"));
		
		Criteria shopCriteria = criteria.createCriteria(Certification.SHOP);
		shopCriteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		
		if(shop != null){
			if(StringUtils.isNotBlank(shop.getShopName())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.START));
			}
			if(shop.getBrands() != null && StringUtils.isNotBlank(brand.getName())){
				shopCriteria.createCriteria(Shop.COLUMN_BRAND).add(Restrictions.like(Brand.COLUMN_NAME,  brand.getName(), MatchMode.START));
			}
		}
		certificationDao.addShopCriteria(shopCriteria,true,null);//添加数据权限
		
		if(userId != null){
			User user = us.find(userId);
			Long ary[] = shopDao.getShops(user);
			shopCriteria.add(Restrictions.in("id",ary));
		}
		
		if(financialId != null){
			criteria.createCriteria(Certification.COLUMN_FINANCIAL).add(Restrictions.eq("id", financialId));
		}
		
		criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		
		return criteria.list();
	}
	
	/*
	 * 增加信息
	 */
	public void saveShop(Shop shop){
		 shopDao.saveShop(shop);
	}
	/**
	 * 查询库存
	 * @param shop
	 * @param brand
	 * @param pageNo
	 * @param pageSize
	 * @param id
	 * @param userId
	 * @return
	 */
	public Page<Shop> findKucun(Shop shop ,Brand brand,int pageNo, int pageSize,Long finalid,User userId,User userOPen){
		Criteria criteria = certificationDao.createCriteria();
		criteria.setProjection(Projections.projectionList().add(Projections.alias(Projections.groupProperty(Certification.SHOP),"shop")).add(Projections.alias(Projections.rowCount(), "cfCount")).add(Projections.countDistinct("shop")));
		criteria.add(Restrictions.eq("state",  CertificationType.INSTOCK));
		
		Criteria shopCriteria = criteria.createCriteria(Certification.SHOP);
		shopCriteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		if(shop != null){
			if(StringUtils.isNotBlank(shop.getShopName())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.ANYWHERE));
			}
		}
		if(!userOPen.getPost().equals(PostType.Admin))
			certificationDao.addShopCriteria(shopCriteria,true,null);//添加数据权限
		
		if(null != brand){
			if(StringUtils.isNotBlank(brand.getName())){
				shopCriteria.createCriteria(Shop.COLUMN_BRAND).add(Restrictions.like(Brand.COLUMN_NAME,  brand.getName(), MatchMode.ANYWHERE));
			}
		}
		if(userId != null){
//			User user = us.find(userId);
			Long ary[] = shopDao.getShops(userId);
			if(null != ary){
				shopCriteria.add(Restrictions.in("id",ary));
			}else{
				return null;
			}
		}
		if(finalid != null){
			criteria.createCriteria(Certification.COLUMN_FINANCIAL).add(Restrictions.eq("id", finalid));
		}
		criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		
//		Long total=(Long)criteria.setProjection(Projections.rowCount()).uniqueResult();
		
		int count = 0;
		count = criteria.list().size();
		
		long pageCount = count / pageSize;
		if (count % pageSize > 0) {
			pageCount++;
		}
		
		if(pageCount < pageNo){
			pageNo = 1;
		}
		
		Page<Shop> page = this.findPageNotAutoCount(criteria, pageNo, pageSize);
		page.setTotalCount(count);
		return page;
		
	}
	
	public Page<Shop> findPageNotAutoCount(Criteria criteria, int pageNumber, int pageSize) {
		Page<Shop> page = new Page<Shop>();
		page.setPageNo(pageNumber);
		page.setPageSize(pageSize);
		page.setAutoCount(false);
		return getEntityDao().findPage(page, criteria);
	}
	/*
	 * 查询信息
	 */
	public Page<Shop> applyShop(Shop shop ,Long financial,int pageNo, int pageSize){
		Criteria criteria = treatyDao.createCriteria();
		criteria.setProjection(Projections.projectionList().add(Projections.alias(Projections.groupProperty(Treaty.COLUMN_SHOP),"shop")).add(Projections.alias(Projections.rowCount(), "cfCount")));
		criteria.add(Restrictions.eq(Treaty.COLUMN_STATE,  true));
		
		Criteria shopCriteria = criteria.createCriteria(Treaty.COLUMN_SHOP);
//		Criteria finalCriteria = criteria.createCriteria("financial");
		shopCriteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		if(shop!=null){
			if(StringUtils.isNotBlank(shop.getShopName())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.ANYWHERE));
			}
			if(StringUtils.isNotBlank(shop.getShopMark())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_MARK, shop.getShopMark(), MatchMode.START));
			}
		}
		if(null != financial){
//			finalCriteria.createCriteria("").add(Restrictions.eq("id", financial));
			criteria.createCriteria("financial").add(Restrictions.eq("id", financial));
		}
		criteria.add(Restrictions.ge("endDate", new Date()));
		criteria.add(Restrictions.eq("unitPrice", 0D));
		criteria.add(Restrictions.eq("collectionWay", "0"));
		criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		return this.findPage(criteria, pageNo, pageSize);
		
	}
	
	public Page<Shop> selectUser(Set<Long> shopiDS ,Shop shop ,Brand brand,int pageNo, int pageSize){
		Criteria criteria = shopDao.createCriteria();
		criteria.addOrder(Order.desc("updatedAt"));
		if(null != shopiDS && shopiDS.size() >0){
			criteria.add(Restrictions.in("id", shopiDS));
		} 
		if(shop!=null){
			if(StringUtils.isNotBlank(shop.getShopMark())){
				criteria.add(Restrictions.like(Shop.COLUMN_SHOP_MARK, shop.getShopMark(), MatchMode.START));
			}
			if(StringUtils.isNotBlank(shop.getShopName())){
				criteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.ANYWHERE));
			}
			if(shop.getArea()!= null){
				if(StringUtils.isNotBlank(shop.getArea().getName())){
					criteria.createCriteria("area").add(Restrictions.eq("name", shop.getArea().getName()));
				}
				
			}
			if(StringUtils.isNotBlank(shop.getCity())){
				criteria.add(Restrictions.eq(Shop.COLUMN_CITY, shop.getCity()));
			}
			if(StringUtils.isNotBlank(shop.getCompany())){
				criteria.add(Restrictions.eq(Shop.COLUMN_COMPANY, shop.getCompany()));
			}
			if(StringUtils.isNotBlank(shop.getProvince())){
				criteria.add(Restrictions.eq(Shop.COLUMN_PROVINCE, shop.getProvince()));
			}
		}
		if(null != brand){
			if( StringUtils.isNotBlank(brand.getName())){
				criteria.createCriteria("brands").add(Restrictions.like(Brand.COLUMN_NAME, brand.getName()));
			}
		}
		if(shop != null && shop.getToDelete() != null ){
			criteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, shop.getToDelete()));
		}else{
			criteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		}
		
		
		
		return this.findPage(criteria, pageNo, pageSize);
		
	}
	
	/**
	 * 新增盘库时选择店铺  -专用
	 * @author xuxl
	 * @param shopiDS
	 * @param shop
	 * @param brand
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public Page<Shop> selectCfShop(Set<Long> shopiDS ,Shop shop,User shoper,int pageNo, int pageSize){
		Criteria criteria = shopDao.createCriteria();
		criteria.addOrder(Order.desc("updatedAt"));
		if(null != shopiDS && shopiDS.size() >0){
			criteria.add(Restrictions.in("id", shopiDS));
		} 
		if(shop!=null){
			if(StringUtils.isNotBlank(shop.getShopMark())){
				criteria.add(Restrictions.like(Shop.COLUMN_SHOP_MARK, shop.getShopMark(), MatchMode.START));
			}
			if(StringUtils.isNotBlank(shop.getShopName())){
				criteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.ANYWHERE));
			}
			if(shop.getArea()!= null){
				if(StringUtils.isNotBlank(shop.getArea().getName())){
					criteria.createCriteria("area").add(Restrictions.eq("name", shop.getArea().getName()));
				}
				
			}
			if(StringUtils.isNotBlank(shop.getCity())){
				criteria.add(Restrictions.eq(Shop.COLUMN_CITY, shop.getCity()));
			}
			if(StringUtils.isNotBlank(shop.getCompany())){
				criteria.add(Restrictions.eq(Shop.COLUMN_COMPANY, shop.getCompany()));
			}
			if(StringUtils.isNotBlank(shop.getProvince())){
				criteria.add(Restrictions.eq(Shop.COLUMN_PROVINCE, shop.getProvince()));
			}
		}
		if(shoper!=null){//如果有根据驻店员查询条件,只查询该驻店员下的店铺
			Long ary[]=theNetworkDao.getShops(shoper);
			if(ary!=null){
				criteria.add(Restrictions.in("id",ary));
			}
			/*else {
				criteria.add(Restrictions.sqlRestriction("1 != 1"));
			}*/
		}
		if(shop != null && shop.getToDelete() != null ){
			criteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, shop.getToDelete()));
		}else{
			criteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		}
		
		
		
		return this.findPage(criteria, pageNo, pageSize);
		
	}
	
	public Page<Shop> findPage(int pageNo, int pageSize){
		Criteria criteria = shopDao.createCriteria();
		Shop shop=new Shop();
		shop.setToDelete(1);
		criteria.add(Restrictions.eq(Shop.COLUMN_TODELETE,shop.getToDelete()));
		return this.findPage(criteria, pageNo, pageSize);
		
	}
	public List<Shop> findAll(){
		return shopDao.findAll();
	}
	/*
	 * 查询店号,店名
	 */
	public boolean shopMarkKey(String shopMark){
		return shopDao.shopMarkKey(shopMark);
	}
	public Shop shopNamekKey(String shopName){
		return shopDao.shopNameKey(shopName);
	}
	public Shop findShopByName(String shopName){
		return shopDao.shopName(shopName);
	}
	/*
	 * 删除信息
	 */
	public boolean deleteShop(Long id){
		return shopDao.deleteShop(id);
	}
	/*
	 * 查询信息
	 */
	public Shop minuteShop(Long id){
		Shop shop=this.find(id);
		return shop;
	}
	/**
	 * 查询所有的店
	 */
	public Map<String, Shop> getAllshop(){
		List<Shop> shops = shopDao.findAll();
		Map<String, Shop> map = new HashMap<String, Shop>();
		for(int i=0;i<shops.size();i++){
			Shop shop= shops.get(i);
			map.put(shop.getShopMark(), shop);
		}
		return map;
	}
	
	public Page<Shop> findAdvanceShop(Shop shop ,int pageNo, int pageSize){
		
		Criteria criteria = shopDao.createCriteria();
		if(shop!=null){
			if(StringUtils.isNotBlank(shop.getShopName())){
				criteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.ANYWHERE));
			}
			if(StringUtils.isNotBlank(shop.getShopMark())){
				criteria.add(Restrictions.like(Shop.COLUMN_SHOP_MARK, shop.getShopMark(), MatchMode.START));
			}
		}
		criteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		
		Criteria treatyCriteria =  treatyDao.createCriteria();
		treatyCriteria.add(Restrictions.eq(Treaty.COLUMN_STATE,  true));
		treatyCriteria.add(Restrictions.ge("endDate", DateUtil.getBeginDate(new Date())));
		treatyCriteria.add(Restrictions.eq("unitPrice", 0D));
//		treatyCriteria.add(Restrictions.eq("collectionWay", "0"));
		treatyCriteria.createCriteria("financial").add(Restrictions.eq("billing", "1"));
		List<Treaty> treatyList= treatyCriteria.list();
		List<Long> shopIds =new ArrayList<Long>();
		if(treatyList!=null){
			for(Treaty tre:treatyList){
				shopIds.add(tre.getShop().getId());
			}
		}
		criteria.add(Restrictions.in("id",shopIds));
		return this.findPage(criteria, pageNo, pageSize);
		
		/*Criteria criteria = treatyDao.createCriteria();
		criteria.setProjection(Projections.projectionList().add(Projections.alias(Projections.groupProperty(Treaty.COLUMN_SHOP),"shop")).add(Projections.alias(Projections.rowCount(), "cfCount")));
		criteria.add(Restrictions.eq(Treaty.COLUMN_STATE,  true));
		
		Criteria shopCriteria = criteria.createCriteria(Treaty.COLUMN_SHOP);
		shopCriteria.add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		if(shop!=null){
			if(StringUtils.isNotBlank(shop.getShopName())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.ANYWHERE));
			}
			if(StringUtils.isNotBlank(shop.getShopMark())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_MARK, shop.getShopMark(), MatchMode.START));
			}
		}
		
		criteria.add(Restrictions.ge("endDate", new Date()));
		criteria.add(Restrictions.eq("unitPrice", 0D));
		criteria.add(Restrictions.eq("collectionWay", "0"));
		criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		*/
		
	}
	
	@Override
	public ShopDao getEntityDao() {
		return shopDao;
	}


	public List<Shop> findShopsByCurrentUser() {
		List<Organization> orgs = organizationService.findShopsByCurrentUser();
		if(orgs == null || orgs.size() < 1){
			return null;
		}
		
		Long[] shopIds = new Long[orgs.size()];
		for (int i = 0; i < shopIds.length; i++) {
			shopIds[i] = orgs.get(i).getObjectId();
		}
	
		return this.findByIds(shopIds);
	}


	/**
	 * @param financialId 
	 * @param dayDate 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Shop> findHaveBusinessShop(Long financialId, String dayDate, User user) {
		List<Organization> orgs = organizationService.findShopsByCurrentUser(user);
		if(orgs == null || orgs.size() < 1){
			return null;
		}
		
		List<Long> shopIds = ReflectionUtils.convertElementPropertyToList(orgs, "objectId");
		
		return findShops(financialId, dayDate, shopIds);
	}


	public List<Shop> findShops(Long financialId, String dayDate, List<Long> shopIds) {
		Date date = DateUtil.getDate(dayDate);
		Criteria criteria = certificationService.getEntityDao().createCriteria();
		criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("shop")).add(Projections.count("shop")));
		
		criteria.add(Restrictions.eq("financial.id", financialId));
		criteria.add(Restrictions.in("shop.id", shopIds));
		
		criteria.add(Restrictions.disjunction().add(Restrictions.conjunction().add(Restrictions.eq("state", CertificationType.ONORDER)).add(Restrictions.le("createdAt", date)))
				.add(Restrictions.conjunction().add(
						Restrictions.in("state", new CertificationType[]{CertificationType.INSTOCK,CertificationType.RELEASEED, CertificationType.RENEWPASS, CertificationType.RENEWOUT}))
												.add(Restrictions.le("warehouseDate", date))
			));
		
		criteria.add(Restrictions.ne("cmImporting", CopyOfCertificationImporting.RENEW));
		List<Object> objs = criteria.list();
		List<Shop> shops = null;
		
		if(objs != null && objs.size() > 0){
			 shops = new ArrayList<Shop>();
			for (int i = 0; i < objs.size(); i++) {
				Object[] obj = (Object[]) objs.get(i);
				if(Long.valueOf(obj[1].toString()) > 0){
					shops.add((Shop) obj[0]);
				}
			}
		}
		return shops;
	}


}
